var points = new Array();
var middle = new Array();
var control = new Array();

function Point(x, y) {
    this.x = x;
    this.y = y;
}
var scale = 0.5;

//points[0] = new Point(50, 120);
//points[1] = new Point(100, 10);
//points[2] = new Point(150, 150);
//points[3] = new Point(200, 200);
//points[4] = new Point(250, 300);
//points[5] = new Point(300, 120);
//points[6] = new Point(350, 350);
//points[7] = new Point(400, 100);
//points[8] = new Point(450, 100);
//points[9] = new Point(500, 30);
//points[10] = new Point(550, 300);

for(var i = 0 ; i <5 ; i++){
    points[i] = new Point(Math.random()*800,Math.random()*400);
}


for (var i = 1; i < points.length; i++) {
    cp = points[i - 1];
    np = points[i];
    middle.push(new Point((cp.x + np.x) / 2, (cp.y + np.y) / 2));
}

for (var i = 1; i < middle.length; i++) {
    cm = middle[i - 1];
    nm = middle[i];
    var x = (cm.x + nm.x) / 2;
    var y = (cm.y + nm.y) / 2;

    var ox = x - points[i].x;
    var oy = y - points[i].y;
    var cx = cm.x - ox;
    var cy = cm.y - oy;
    var nx = nm.x - ox;
    var ny = nm.y - oy;
    
    var offset_c_x = (cx-points[i].x)*scale;
    var offset_c_y = (cy-points[i].y)*scale;
    var offset_n_x = (nx-points[i].x)*scale;
    var offset_n_y = (ny-points[i].y)*scale;
    


    control.push(new Point(points[i].x + offset_c_x, points[i].y + offset_c_y));
    control.push(new Point(points[i].x + offset_n_x, points[i].y + offset_n_y));
}

var map = document.getElementById("map");
var context = map.getContext("2d");
context.beginPath();
for (var i = 0; i < points.length; i++) {
    context.lineTo(points[i].x, points[i].y);
}
context.stroke();

context.beginPath();
context.strokeStyle = "pink";
for (var i = 0; i < middle.length; i++) {
    context.lineTo(middle[i].x, middle[i].y);
}
context.stroke();

context.beginPath();
context.strokeStyle = "red";
for (var i = 1; i < control.length; i = i + 2) {
    context.moveTo(control[i - 1].x, control[i - 1].y);
    context.lineTo(control[i].x, control[i].y);
}
context.stroke();

context.beginPath();
context.strokeStyle = "green";
context.moveTo(points[0].x, points[0].y);
for (var i = 1; i < points.length; i++) {
    var  len = (i-1)*2-1;
    if (i === 1) {
        context.bezierCurveTo(control[i - 1].x, control[i - 1].y, control[i - 1].x, control[i - 1].y, points[i].x, points[i].y);
    }else if (i !== (points.length-1)){
        context.bezierCurveTo(control[len].x, control[len].y, control[len+1].x, control[len+1].y, points[i].x, points[i].y);
    }else{
        context.bezierCurveTo(control[len].x, control[len].y, control[len].x, control[len].y, points[i].x, points[i].y);
    }
}
context.stroke();

